import React from 'react';
import PropTypes from 'prop-types';
import {Table, Card, Button, Row, Col, Form, Spin} from 'antd';
import routes from './routes';
import {newValidator} from './validator';
import Return from '../common/Return';
import {injectIntl, language} from './intl';
import {FORM_OPTIONS, TABLE, DATETIME_FORMAT, FORM_ROW_OPTIONS} from '../constants';
import {partDeliveryType, currency, transportType} from '../Enum';
import WrappedSelect from '../common/WrappedSelect';
import TextInput from 'Shared/components/TextInput';
import DeliveryOrderSelectPanel from './DeliveryOrderSelectPanel';
import {conventEnumValueToString, formatAmount, formatDateTime} from '../utils';

const partDeliveryTypeList = partDeliveryType.toList(language);
const FormItem = Form.Item;
export class DeliveryOrderPanel extends React.PureComponent {
    state = {
        isValidate: false,
        hasOperat: false,
        loading: false,
        data: {
            deliveryStatus: partDeliveryType.发货过账
        },
        details: [],
        showDeliveryOrder: false
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onSubmit = () => {
        this.setState({
            loading: true
        });
        const {data, details} = this.state;
        const isValid = newValidator(details);
        if(!isValid) {
            this.setState({
                isValidate: true,
                loading: false
            });
            return;
        }
        this.props.onSubmit(data, details)
            .then(res => {
                if(res.success)
                    this.props.successReturn();
                if(!this.isunmount)
                    this.setState({loading: false});
            });
    }
    onClickReturnBtn = () => {
        this.props.onCancel();
    }
    onSelectDeliveryOrder = data => {
        const retailDetails = this.state.details || [];
        data.forEach(item => {
            const index = retailDetails.findIndex(v => v.id === item.id);
            if(index === -1)
                retailDetails.push({
                    id: item.id,
                    dealerCode: item.dealerCode,
                    brandCode: item.brandCode,
                    brandName: item.brandName,
                    sapDeliveryCode: item.sapDeliveryCode,
                    sapTransferOrderCode: item.sapTransferOrderCode,
                    partSaleOrderCode: item.partSaleOrderCode,
                    partOrderTypeName: item.partOrderTypeName,
                    itemCount: item.itemCount,
                    totalAmount: item.totalAmount,
                    transportType: item.transportType,
                    submitDate: item.submitDate,
                    status: item.status,
                    currency: item.currency,
                });
        });
        this.setState({
            details: [...retailDetails],
            hasOperat: true,
            showDeliveryOrder: false
        });
    }
    onClickDeliveryOrder = () => {
        this.setState({showDeliveryOrder: true});
    }
    onCloseDeliveryOrder = () => {
        this.setState({showDeliveryOrder: false});
    }
    render() {
        const {data, details} = this.state;
        const {formatMessage} = this.props.intl;
        if(this.props.brands.length === 1 && !this.props.id) {
            data.brandId = this.props.brands[0].value;
            data.brandName = this.props.brands[0].text;
        }
        const currentSelectRowkeys = details.map(item => item.id);
        const validateRemark = data.remark && data.remark.length > 200 && this.state.isValidate ? 'error' : null;
        const columns = [
            {
                title: formatMessage({
                    id: 'deliveryOrderPanel.column.brandCode',
                    defaultMessage: '品牌'
                }),
                dataIndex: 'brandCode',
                render: (text, r) => `(${r.brandCode})${r.brandName}`
            },
            {
                title: formatMessage({
                    id: 'deliveryOrderPanel.column.dealerCode',
                    defaultMessage: '总代'
                }),
                dataIndex: 'dealerCode'
            },
            {
                title: formatMessage({
                    id: 'deliveryOrderPanel.column.sapDeliveryCode',
                    defaultMessage: '交货单号'
                }),
                dataIndex: 'sapDeliveryCode'
            }, {
                title: formatMessage({
                    id: 'deliveryOrderPanel.column.sapTransferOrderCode',
                    defaultMessage: '调拨单号'
                }),
                sorter: true,
                dataIndex: 'sapTransferOrderCode'
            }, {
                title: formatMessage({
                    id: 'deliveryOrderPanel.column.partSaleOrderCode',
                    defaultMessage: '订单编号'
                }),
                dataIndex: 'partSaleOrderCode'
            }, {
                title: formatMessage({
                    id: 'deliveryOrderPanel.column.partOrderTypeName',
                    defaultMessage: '订单类型'
                }),
                dataIndex: 'partOrderTypeName'
            }, {
                title: formatMessage({
                    id: 'deliveryOrderPanel.column.status',
                    defaultMessage: '状态'
                }),
                dataIndex: 'status',
                render: text => conventEnumValueToString(partDeliveryType, text)
            }, {
                title: formatMessage({
                    id: 'deliveryOrderPanel.column.transportType',
                    defaultMessage: '运输方式'
                }),
                dataIndex: 'transportType',
                render: text => conventEnumValueToString(transportType, text)
            }, {
                title: formatMessage({
                    id: 'deliveryOrderPanel.column.submitDate',
                    defaultMessage: '订单提报日期'
                }),
                dataIndex: 'submitDate',
                render: text => formatDateTime(text, DATETIME_FORMAT)
            }, {
                title: formatMessage({
                    id: 'deliveryOrderPanel.column.currency',
                    defaultMessage: '币种'
                }),
                dataIndex: 'currency',
                render: text => conventEnumValueToString(currency, text)
            }, {
                title: formatMessage({
                    id: 'deliveryOrderPanel.column.itemCount',
                    defaultMessage: '品种数'
                }),
                dataIndex: 'itemCount'
            }, {
                title: formatMessage({
                    id: 'deliveryOrderPanel.column.totalAmount',
                    defaultMessage: '总金额'
                }),
                dataIndex: 'totalAmount',
                render: text => formatAmount(text)
            }
        ];
        return (
            <div>
                <Spin spinning={this.state.loading}>
                    <Form className="form-standard">
                        <Card title={formatMessage({
                            id: 'deliveryOrderPanel.card.delivery.title',
                            defaultMessage: '交货单目标状态'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'deliveryOrderPanel.operation.deliveryStatus',
                                        defaultMessage: '交货单状态'
                                    })} {...FORM_OPTIONS.item}>
                                        <WrappedSelect
                                            disabled={true}
                                            name="deliveryStatus"
                                            value={data.deliveryStatus}
                                            options={partDeliveryTypeList}
                                            onChange={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_ROW_OPTIONS.item} validateStatus={validateRemark}>
                                        <TextInput
                                            type="textarea"
                                            name="remark"
                                            value={data.remark}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        <Card
                            title={formatMessage({
                                id: 'newPanel.operation.detail',
                                defaultMessage: '订单清单'
                            })}
                            extra={<div>
                                <Button
                                    size="small"
                                    onClick={this.onClickDeliveryOrder}>
                                    {formatMessage({
                                        id: 'newPanel.operation.newDetail',
                                        defaultMessage: '新增交货单'
                                    })}
                                </Button>
                            </div>}>
                            <Table
                                className="white-space-nowrap"
                                columns={columns}
                                loading={this.state.isLoading}
                                rowKey="id"
                                dataSource={details}
                                rowClassName={this.setRowClassName}
                                pagination={false}
                                {...TABLE} />
                        </Card>
                    </Form>
                    <Card>
                        <Row>
                            <Col className="col-align-right">
                                <Button key="audit"
                                    onClick={this.onSubmit}
                                    type="primary"
                                    loading={this.state.loading}>
                                    {formatMessage({
                                        id: 'deliveryOrderPanel.btn.submit',
                                        defaultMessage: '保存'
                                    })}</Button>
                            </Col>
                        </Row>
                    </Card>
                    {
                        this.state.showDeliveryOrder &&
                        <DeliveryOrderSelectPanel
                            selectKey={data.code}
                            currentSelectRowkeys={currentSelectRowkeys}
                            onCancel={this.onCloseDeliveryOrder}
                            onSelect={this.onSelectDeliveryOrder} />
                    }
                </Spin>
                <div className="page-toolbar">
                    <Return
                        onConfirm={this.onClickReturnBtn}
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

DeliveryOrderPanel.propTypes = {
    data: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    brands: PropTypes.array,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {tableSearch, onSubmit} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id,
            currency: item.currency
        })) : [];
        return brands;
    }
);
const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const mapStateToProps = state => ({
    data: getData(state),
    brands: getinitEnumData(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: (data, details) => dispatch(onSubmit(data, details)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(DeliveryOrderPanel));
